﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using kk.components.contracts;
using kk.messages.contracts.DataModel;

namespace kk.preiskategorieadapter
{
    public class PreiskategorieAdapter : IPreiskategorieAdapter
    {
        private readonly string preiskategorienFilename;

        public PreiskategorieAdapter() : this("preiskategorien.txt"){}
        internal PreiskategorieAdapter(string preiskategorienFilename)
        {
            this.preiskategorienFilename = preiskategorienFilename;
        }


        public void ProcessPreiskategorien(Request<IEnumerable<Preiskategorie>> request)
        {
            request.ResponsePin(ParseFile(this.preiskategorienFilename));
        }


        public static IEnumerable<Preiskategorie> ParseFile(string filename)
        {
            return File.ReadAllLines(filename)
                       .Where(l => l.Trim() != "")
                       .Aggregate(new List<Preiskategorie>(), 
                                  (list, line) => { 
                                                     list.Add(ParseSingle(line)); 
                                                     return list; 
                                                  });
        }

        
        internal static Preiskategorie ParseSingle(string preiskategorieText)
        {
            var parts = preiskategorieText.Split('=');
            return new Preiskategorie(parts[0].Trim()[0], double.Parse(parts[1]));
        }
    }
}
